package itsen.com.bduidemo.modle.net;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.Map;
/**
 * Created by zhoud on 2018/5/5.
 */

public class SoapCommunicator {

    private static final int TIMEOUT_MS = 10000;

    public static final String ERROR_PREFIX = "error_";
    public static final String ERROR_COMMON = ERROR_PREFIX + "common";
    public static final String ERROR_TIMEOUT = ERROR_PREFIX + "timeout";

    //用来判断是否call调用返回的是error
    public static boolean isError(String str) {
        return str.contains(ERROR_PREFIX);
    }

    /**
     * @param wsdlUrl ip地址
     * @param namespace 命名空间
     * @param methodName 请求方法
     * @param params 请求参数
     * @return
     */
    public String call(String wsdlUrl, String namespace, String methodName, Map<String, Object> params) {

        try {
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            SoapObject request = new SoapObject(namespace, methodName);

            //设置参数
            if (params != null && !params.isEmpty()) {
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    PropertyInfo info = new PropertyInfo();
                    info.setNamespace(namespace);
                    info.setName(entry.getKey());
                    info.setValue(entry.getValue());
                    request.addProperty(info);
                }
            }
            envelope.setOutputSoapObject(request);
            HttpTransportSE ht = new HttpTransportSE(wsdlUrl, TIMEOUT_MS);
            ht.call(null, envelope);
            Object response = envelope.getResponse();
            if (response != null) {
                return response.toString();
            } else {
                return ERROR_COMMON;
            }
        } catch (Exception e) {
            e.printStackTrace();

            if (e instanceof java.net.SocketTimeoutException) {
                return ERROR_TIMEOUT;
            }

            return ERROR_COMMON;
        }
    }
}
